import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'

const prisma = new PrismaClient()

interface HealthDataSummary {
  sleep: {
    daily_total_sleep_duration: number[]
    daily_deep_sleep_duration: number[]
    todayDetails?: {
      deepSleep: number
      lightSleep: number
      remSleep: number
      awakeTime: number
      totalSleep: number
    }
  }
  heart: {
    daily_avg_hr: number[]
    daily_max_hr: number[]
    daily_min_hr: number[]
    daily_hrv: number[]
  }
  activity: {
    daily_step_count: number[]
  }
  blood_glucose: Array<{
    reading: number
    context: string
    timestamp: string
  }>
  blood_pressure: Array<{
    systolic: number
    diastolic: number
    timestamp: string
  }>
  respiratory: {
    daily_avg_spo2: number[]
    daily_min_spo2: number[]
    daily_max_spo2: number[]
  }
  dates: string[]
}

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const userId = searchParams.get('userId')

    if (!userId) {
      return NextResponse.json(
        { error: '缺少必要参数: userId' },
        { status: 400 }
      )
    }

    // 计算14天前的时间戳
    const fourteenDaysAgo = new Date()
    fourteenDaysAgo.setDate(fourteenDaysAgo.getDate() - 14)
    const fourteenDaysAgoTimestamp = BigInt(fourteenDaysAgo.getTime())

    console.log('🔍 获取用户健康数据摘要:', { userId, fourteenDaysAgo: fourteenDaysAgo.toISOString() })

    // 获取最近14天的所有健康数据（一次查询）
    const allHealthLogs = await prisma.yh_logs.findMany({
      where: {
        user_id: parseInt(userId),
        timestamp: {
          gte: fourteenDaysAgoTimestamp
        },
        deleted_at: 0,
        type: {
          in: ['sleep', 'heart_rate', 'hrv', 'step', 'spo2', 'blood_glucose', 'blood_pressure']
        }
      },
      orderBy: [
        { timestamp: 'asc' }
      ]
    })

    console.log('📊 获取到健康数据记录数:', allHealthLogs.length)

    // 按日期分组数据
    const dailyData = new Map<string, any[]>()

    allHealthLogs.forEach(log => {
      try {
        const logData = typeof log.data === 'string' ? JSON.parse(log.data) : log.data
        let timestamp

        // 处理时间戳格式
        if (logData.ts) {
          // 优先使用数据中的时间戳
          timestamp = parseInt(logData.ts)
          if (timestamp < 10000000000) {
            timestamp = timestamp * 1000
          }
        } else {
          // 使用记录的时间戳
          timestamp = parseInt(log.timestamp.toString())
          if (timestamp < 10000000000) {
            timestamp = timestamp * 1000
          }
        }

        const date = new Date(timestamp)
        const dateKey = date.toISOString().split('T')[0] // YYYY-MM-DD格式

        if (!dailyData.has(dateKey)) {
          dailyData.set(dateKey, [])
        }
        dailyData.get(dateKey)!.push({
          type: log.type,
          data: logData,
          timestamp: timestamp
        })
      } catch (error) {
        console.error('解析健康数据失败:', error, log.data)
      }
    })

    // 生成最近14天的日期数组
    const dates = []
    for (let i = 13; i >= 0; i--) {
      const date = new Date()
      date.setDate(date.getDate() - i)
      dates.push(date.toISOString().split('T')[0])
    }

    // 初始化汇总数据
    const summary: HealthDataSummary = {
      sleep: {
        daily_total_sleep_duration: new Array(14).fill(0),
        daily_deep_sleep_duration: new Array(14).fill(0)
      },
      heart: {
        daily_avg_hr: new Array(14).fill(0),
        daily_max_hr: new Array(14).fill(0),
        daily_min_hr: new Array(14).fill(0),
        daily_hrv: new Array(14).fill(0)
      },
      activity: {
        daily_step_count: new Array(14).fill(0)
      },
      blood_glucose: [],
      blood_pressure: [],
      respiratory: {
        daily_avg_spo2: new Array(14).fill(0),
        daily_min_spo2: new Array(14).fill(0),
        daily_max_spo2: new Array(14).fill(0)
      },
      dates: dates
    }

    // 处理每一天的数据
    dates.forEach((date, index) => {
      const dayData = dailyData.get(date) || []

      dayData.forEach(item => {
        try {
          const data = item.data

          switch (item.type) {
            case 'sleep':
              // 解析睡眠质量数组数据（参考 user-detail-inline.tsx 第1216-1228行）
              if (data.arraySleepQuality && Array.isArray(data.arraySleepQuality)) {
                const sleepData = data.arraySleepQuality
                const unitLength = parseInt(data.sleepUnitLength || '1')

                // 统计各阶段时长（分钟）
                // 深度睡眠: 1
                // 浅睡眠: 2
                // REM睡眠: 3
                // 清醒: 所有非1、2、3的值
                const deepSleep = sleepData.filter((q: any) => {
                  const val = typeof q === 'string' ? parseInt(q) : q
                  return val === 1
                }).length * unitLength
                
                const lightSleep = sleepData.filter((q: any) => {
                  const val = typeof q === 'string' ? parseInt(q) : q
                  return val === 2
                }).length * unitLength
                
                const remSleep = sleepData.filter((q: any) => {
                  const val = typeof q === 'string' ? parseInt(q) : q
                  return val === 3
                }).length * unitLength
                
                const awake = sleepData.filter((q: any) => {
                  const val = typeof q === 'string' ? parseInt(q) : q
                  return val !== 1 && val !== 2 && val !== 3
                }).length * unitLength
                
                const totalSleep = deepSleep + lightSleep + remSleep

                // 累加汇总数据（一天可能有多条睡眠记录）
                summary.sleep.daily_total_sleep_duration[index] += totalSleep
                summary.sleep.daily_deep_sleep_duration[index] += deepSleep

                // 如果这是今天的数据，累加到详细信息中
                if (index === dates.length - 1) {
                  if (!summary.sleep.todayDetails) {
                    summary.sleep.todayDetails = {
                      deepSleep: 0,
                      lightSleep: 0,
                      remSleep: 0,
                      awakeTime: 0,
                      totalSleep: 0
                    }
                  }
                  summary.sleep.todayDetails.deepSleep += deepSleep
                  summary.sleep.todayDetails.lightSleep += lightSleep
                  summary.sleep.todayDetails.remSleep += remSleep
                  summary.sleep.todayDetails.awakeTime += awake
                  summary.sleep.todayDetails.totalSleep += totalSleep
                }
              }
              break

            case 'heart_rate':
              if (data.avgHeartRate !== undefined) {
                summary.heart.daily_avg_hr[index] = Math.round(data.avgHeartRate)
              }
              if (data.maxHeartRate !== undefined) {
                summary.heart.daily_max_hr[index] = Math.round(data.maxHeartRate)
              }
              if (data.minHeartRate !== undefined) {
                summary.heart.daily_min_hr[index] = Math.round(data.minHeartRate)
              }
              break

            case 'hrv':
              if (data.hrv !== undefined) {
                summary.heart.daily_hrv[index] = Math.round(data.hrv)
              }
              break

            case 'step':
              if (data.detailMinterStep !== undefined) {
                summary.activity.daily_step_count[index] = parseInt(data.detailMinterStep) || 0
              }
              break

            case 'blood_glucose':
              if (data.blood_glucose_reading !== undefined && data.blood_glucose_context !== undefined) {
                summary.blood_glucose.push({
                  reading: parseFloat(data.blood_glucose_reading),
                  context: data.blood_glucose_context,
                  timestamp: new Date(item.timestamp).toISOString()
                })
              }
              break

            case 'blood_pressure':
              if (data.systolic !== undefined && data.diastolic !== undefined) {
                summary.blood_pressure.push({
                  systolic: parseInt(data.systolic),
                  diastolic: parseInt(data.diastolic),
                  timestamp: new Date(item.timestamp).toISOString()
                })
              }
              break

            case 'spo2':
              if (data.avgSpo2 !== undefined) {
                summary.respiratory.daily_avg_spo2[index] = Math.round(data.avgSpo2 * 100) / 100
              }
              if (data.minSpo2 !== undefined) {
                summary.respiratory.daily_min_spo2[index] = Math.round(data.minSpo2 * 100) / 100
              }
              if (data.maxSpo2 !== undefined) {
                summary.respiratory.daily_max_spo2[index] = Math.round(data.maxSpo2 * 100) / 100
              }
              break
          }
        } catch (error) {
          console.error('处理健康数据项失败:', error, item)
        }
      })
    })

    console.log('✅ 健康数据汇总完成:', {
      days: dates.length,
      sleepDays: summary.sleep.daily_total_sleep_duration.filter(v => v > 0).length,
      heartDays: summary.heart.daily_avg_hr.filter(v => v > 0).length,
      activityDays: summary.activity.daily_step_count.filter(v => v > 0).length,
      bloodGlucoseCount: summary.blood_glucose.length,
      bloodPressureCount: summary.blood_pressure.length,
      respiratoryDays: summary.respiratory.daily_avg_spo2.filter(v => v > 0).length
    })

    return NextResponse.json({
      success: true,
      data: summary
    })

  } catch (error) {
    console.error('健康数据汇总API错误:', error)
    return NextResponse.json(
      { error: '服务器内部错误' },
      { status: 500 }
    )
  }
}
